/*
 * Copyright (c) 2010, okazoh_tk. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "alkes/core/BitArray.h"
#include "alkes/core/Macro.h"
#include "alkes/core/Memory.h"
#include <string.h>

namespace alkes {

#define DATA_BITS   (sizeof(uintptr_t) * 8)
#define BITS_PTR()  ((DATA_BITS < max_count_) ? data_.buffer_ : &data_.bits_)
#define BIT_MASK    (DATA_BITS - 1)

BitArray::BitArray(uint32_t count)
: max_count_(count)
{
    if (DATA_BITS < max_count_)
    {
        uint32_t bytes = ((count + (DATA_BITS - 1)) / DATA_BITS) * sizeof(uintptr_t);
        data_.buffer_ = (uintptr_t*)alkes_malloc(bytes);
        memset(data_.buffer_, 0, bytes);
    }
    else
    {
        data_.bits_ = 0;
    }
}

BitArray::~BitArray()
{
    if (DATA_BITS < max_count_)
    {
        alkes_free(data_.buffer_);
    }
}

bool BitArray::operator [](uint32_t idx) const
{
    const uintptr_t* bits = BITS_PTR();
    return AL_BITS_IS_ON(bits[idx / DATA_BITS], (uintptr_t)1 << (idx % DATA_BITS));
}

void BitArray::setFlag(uint32_t idx, bool is_on)
{
    if (is_on)
    {
        uintptr_t* bits = BITS_PTR();

        AL_BITS_ON(bits[idx / DATA_BITS], (uintptr_t)1 << (idx % DATA_BITS));
    }
    else
    {
        clearFlag(idx);
    }
}

void BitArray::clearFlag(uint32_t idx)
{
    uintptr_t* bits = BITS_PTR();

    AL_BITS_OFF(bits[idx / DATA_BITS], (uintptr_t)1 << (idx % DATA_BITS));
}

}
